#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>

#define N 10

void runchild()
{
    int cnt = 5;
    while(cnt){
        printf("I am a child Process,pid:%d,ppid:%d\n",getpid(),getppid());
        cnt--;
    }
}

int main()
{
//    for(int i = 0;i < N;i++){
//        pid_t id = fork();
//        if(id == 0){
//            runchild();
//            exit(0);
//        }
//        printf("create child %d success\n",id);//只有父进程可以走到这里
//    }
//    sleep(10);
//    for(int i = 0;i < N;i++){
//        pid_t id = wait(NULL);
//      if(id > 0){
//            printf("wait %d success\n",id);
//        }
//    }
//    sleep(10);
    pid_t id = fork();
    if(id < 0){
        perror("fork:");
        return 1;
    }
    else if(id == 0){
        int cnt = 5;
        while(cnt){
            printf("I am child,pid:%d,ppid:%d,cnt:%d\n",getpid(),getppid(),cnt--);
            sleep(1);
        }
        exit(1);
    }
    else{
        //int cnt = 10;
        //while(cnt){
        //    printf("I am father,pid:%d,ppid:%d,cnt:%d\n",getpid(),getppid(),cnt--);
        //    sleep(1);
        //}
        //pid_t ret = wait(NULL);
        while(1){
            int status = 0;
            pid_t ret = waitpid(id,&status,WNOHANG);//非阻塞循环:WNOHANG
            if(ret > 0){
                if(WIFEXITED(status)) printf("wait success,exit code:%d\n",WEXITSTATUS(status));
                else{
                    printf("进程出异常了！！\n");
                }
                break;
            }
            else if(ret < 0){
                printf("wait failed\n");
                break;
            }
            else{//ret = 0 : 进程还没结束，我再等等
                printf("子进程还没退出，再等等\n");
                //sleep(1);
            }
        }
            //if(ret == id){
            //    printf("wait sucess,ret: %d,exit sig:%d,exit code:%d\n",ret,status&0x7F,(status >> 8)&0xFF);
            //}
        sleep(5);
    }
    return 0;
}

